package jmind.core.geo;

import java.net.URLEncoder;

import javax.script.Invocable;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

import jmind.core.support.HttpUtil;
import jmind.base.util.DataUtil;

import com.mongodb.BasicDBList;
import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;

public class SoGouGeo implements Geo {

    public static void main(String[] args) {
        SoGouGeo geo = new SoGouGeo();
        GLocation address = geo.getByIp();
        System.out.println(address);
    }

    /**
     * 地址解析请求的http网址：

    http://api.go2map.com/engine/api/geocoder/output?parameters
    其中，output 可能是以下任何一个值：
    json（建议）表示以 JavaScript 对象表示法 (JSON) 的形式输出
    xml 表示以 XML 的形式输出
     */
    @Override
    public GLocation getByAddress(String address, String city) {
        try {
            String url = "http://api.go2map.com/engine/api/geocoder/json?addr=" + URLEncoder.encode(address, "UTF-8");
            if (!DataUtil.isEmpty(city)) {
                url += "&city=" + URLEncoder.encode(city, "UTF-8");
            }
            String content = HttpUtil.get(url);
            DBObject jo = (DBObject) JSON.parse(content);
            String status = (String) jo.get("status");
            if ("ok".equals(status)) {
                BasicDBObject res = (BasicDBObject) jo.get("response");
                GLocation gl = new GLocation();
                gl.setAddress(res.getString("match"));
                gl.setCity(res.getString("city"));
                gl.setProvince(res.getString("province"));
                gl.setX(res.getDouble("x"));
                gl.setY(res.getDouble("y"));
                return gl;
            } else {
                System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

    /**
     * points 必填  需要转换的坐标串。 可以为一个或多个坐标点。坐标点用经度坐标+逗号+纬度坐标来表示，多个点用分号隔开。例如：23112,888990;32353,8993233;…….
    type    必填  源坐标的所属类型，取值范围：
    type=0 sogou坐标 
    type=1 对应标准经纬度 
     */
    @Override
    public GLocation getByCoordinate(String latitude, String longitude) {
        String url = "http://api.go2map.com/engine/api/regeocoder/json?type=1&points=" + longitude + "," + latitude;
        String content = HttpUtil.get(url);
        DBObject jo = (DBObject) JSON.parse(content);
        String status = (String) jo.get("status");
        if ("ok".equals(status)) {
            BasicDBList data = (BasicDBList) ((BasicDBObject) jo.get("response")).get("data");
            BasicDBObject res = (BasicDBObject) data.get(0);
            GLocation gl = new GLocation();
            gl.setAddress(res.getString("address"));
            gl.setCity(res.getString("city"));
            gl.setProvince(res.getString("province"));
            gl.setDistrict(res.getString("district"));
            return gl;
        } else {
            System.out.println(content);
        }
        return null;
    }

    public double getDistance(double lat1, double lng1, double lat2, double lng2) {
        String js = HttpUtil.get("http://api.go2map.com/maps/js/api_v2.5.1.js");
        ScriptEngineManager factory = new ScriptEngineManager();
        try {
            // create engine by name
            ScriptEngine engine = factory.getEngineByName("JavaScript");
            engine.eval(js);
            Invocable invoke = (Invocable) engine;
            Object object = invoke.invokeFunction("sogou.maps.LatLng", 39.99676822857143, 116.33298485714285);
            System.out.println(object);
        } catch (Exception e) {
            e.printStackTrace();

        }
        return 0;
    }

    public GLocation getByIp() {
        String url = "http://api.go2map.com/engine/api/ipcity/json?contenttype=utf8";
        String content = HttpUtil.get(url);
        DBObject jo = (DBObject) JSON.parse(content);
        String status = (String) jo.get("status");
        if ("ok".equals(status)) {
            BasicDBObject res = (BasicDBObject) jo.get("response");
            GLocation gl = new GLocation();
            gl.setAddress(res.getString("match"));
            gl.setCity(res.getString("city"));
            gl.setProvince(res.getString("province"));
            gl.setX((Number) res.get("x"));
            gl.setY((Number) res.get("y"));
            return gl;
        } else {
            System.out.println(content);
        }
        return null;
    }

}
